// pages/shop/show.js

import { makePhoneCall, datetimeFormat } from '../../utils/util'

import {
  getSellerInfo,
  getProductsInfo,
  getProductTypes,
  getReviews,
  addQuasiOrder
} from '../../utils/apis'
import { alert } from '../../utils/util'

var initOrder = {
  price: 0, // 折扣前商品金额 + packagePrice + expressPrice
  payPrice: 0, // 折扣后商品金额 + packagePrice + expressPrice
  productPrice: 0, // 商品金额
  packagePrice: 0, // 打包金额
  expressPrice: 0, // 配送金额
  productList: {}, // 订单商品列表 => 下单操作转为数组
  totalNum: 0 // 所选商品总数
}

const app = getApp()

Page({
  data: {
    tabs: ['商品', '评价', '商家'],
    activeIndex: 0,
    copyProductsInfo: [], // 购物车数据
    activeMenuIndex: 0,
    showCart: false,

    showSubGoods: false,
    order: initOrder,

    review: {
      hasMore: true,
      loading: false,
      page: 0,
      size: 10,
      list: []
    },
    activeProduct: '', // 所选商品类型
    productTypes: [], // 商品类型
    productsInfo: [] // 商品列表
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.id = options.id || 4

    this.loadData()
    this.loadProductsList()
  },

  loadData() {
    var that = this
    var id = this.id
    wx.showNavigationBarLoading()
    // 获取店铺详情
    getSellerInfo({
      id: id
    })
      .then(data => {
        let weekStr = ''
        if (data.workDay) {
          var weekArr = data.workDay.split(',')

          weekArr.forEach(item => {
            switch (item) {
              case '1':
                weekStr += '周一 '
                break
              case '2':
                weekStr += '周二 '
                break
              case '3':
                weekStr += '周三 '
                break
              case '4':
                weekStr += '周四 '
                break
              case '5':
                weekStr += '周五 '
                break
              case '6':
                weekStr += '周六 '
                break
              case '7':
                weekStr += '周日'
                break
              default:
                weekStr += weekArr
                break
            }
          })
        }
        that.setData({
          info: Object.assign(data, {
            weekDayStr: weekStr
          }),
          order: Object.assign(this.data.order, {
            expressPrice: data.expressPrice, // 配送费
            storeId: data.id, // 所属店铺id
            bossId: data.bossId, // 所属商家
            arriveTime: data.arriveTime // 送达时间
          })
        })
        console.log(this.data.order)
        wx.setNavigationBarTitle({
          title: data.name
        })

        wx.hideNavigationBarLoading()
      })
      .catch(err => {
        if (err.code == 1120002) {
          // 老板不在店
          alert(err.message, function() {
            wx.navigateBack()
          })
        }
      })
  },

  // 获取商品类型 => 获取商品列表
  loadProductsList() {
    var that = this
    var { copyProductsInfo } = that.data
    var id = this.id
    wx.showNavigationBarLoading()
    // 获取商品类型
    getProductTypes({
      id: id
    })
      .then(data => {
        console.log('productTypes:', data)
        that.setData({
          productTypes: data
        })

        // 获取商品列表
        return getProductsInfo({ storeId: id, productTypeId: data[0].id })
        // return getProductsInfo({ storeId: 1, productTypeId: 10 })
      })
      .then(data => {
        if (data.products) {
          console.log('getProductsInfo:', data)
          that.setData({
            productsInfo: data.products,
            copyProductsInfo: copyProductsInfo.concat(data.products)
          })
        }
      })
  },

  // 获取商家评论列表
  loadReview() {
    var that = this
    var id = this.id
    var {
      review: { page, loading, size = 20 }
    } = this.data

    if (loading) {
      return
    }

    this.setData({
      'review.loading': true
    })

    getReviews({
      id: id,
      page: page,
      size: size
    }).then(data => {
      var {
        review: { list }
      } = that.data
      if (data.comments) {
        that.setData({
          'review.list': list ? list.concat(data.comments) : data.comments,
          'review.loading': false,
          'review.page': page + 1,
          'review.hasMore': data.count > (page + 1) * size
        })
      } else {
        that.setData({
          'review.loading': false,
          'review.hasMore': data.count > (page + 1) * size
        })
      }
    })
  },

  tabClick: function(e) {
    var that = this
    switch (e.currentTarget.id) {
      case '1':
        if (this.data.review.list.length === 0) {
          // 获取商家评论列表
          this.loadReview()
        }
        break
      default:
        break
    }
    this.setData({
      activeIndex: e.currentTarget.id
    })
  },

  // 选择商品
  chooseProduct: function(e) {
    this.setData({
      activeProduct: e.currentTarget.id
    })
  },

  swiperChange(e) {
    var { current } = e.detail
    this.setData({
      activeIndex: current
    })
  },

  // 点击商品种类筛选请求对应商品列表
  menuClick: function(e) {
    let that = this
    var { copyProductsInfo } = that.data
    let id = this.id
    let { goodsId } = e.currentTarget.dataset
    this.setData({
      activeMenuIndex: e.currentTarget.id
    })
    console.log('productTypeId:', goodsId)
    getProductsInfo({ storeId: id, productTypeId: goodsId }).then(res => {
      // 清空当前列表
      that.setData({ productsInfo: [] })
      if (res.products) {
        console.log(`${goodsId} 商品：`, res)
        that.setData({
          productsInfo: res.products,
          copyProductsInfo: copyProductsInfo.concat(res.products)
        })
      }
    })
  },

  // 加号
  increase(e) {
    let { order, copyProductsInfo } = this.data // 购物车数据，商品列表
    let { productList } = order // 商品列表
    let {
      goodsId,
      activeIndex,
      name,
      price,
      payPrice
    } = e.currentTarget.dataset // 商品 id， 商品索引
    let product = copyProductsInfo.filter(v => v.id === goodsId)[0] // 当前商品

    order.totalNum++
    order.price += +product.price
    order.payPrice += +product.payPrice
    order.packagePrice += +product.packagePrice
    order.productPrice += +product.payPrice
    // 判断当前商品是否在购物车
    if (!Object.values(productList).some(v => v.productId == goodsId)) {
      productList[goodsId] = {
        productId: goodsId,
        productNum: 1,
        productName: name,
        productPrice: price,
        productPayPrice: payPrice
      }
    } else {
      productList[goodsId].productNum++
    }

    this.setData({
      order
    })

    console.log('order:', order)
  },

  // 减号
  decrease(e) {
    let { order, copyProductsInfo } = this.data // 购物车数据，商品列表
    let { productList } = order // 商品列表
    let { goodsId, activeIndex } = e.currentTarget.dataset // 商品 id， 商品索引
    let product = copyProductsInfo.filter(v => v.id === goodsId)[0] // 当前商品

    order.totalNum--
    order.price -= +product.price
    order.payPrice -= +product.payPrice
    order.packagePrice -= +product.packagePrice
    order.productPrice -= +product.payPrice
    // 商品数量--
    productList[goodsId].productNum--

    if (productList[goodsId].productNum == 0) {
      delete productList[goodsId]
    }

    this.setData({
      order
    })

    console.log('order:', order)
  },

  calcGoodsNums(goods) {
    var goodsNums = {}
    for (let i = 0, len = goods.length; i < len; i++) {
      let { goods_id, num } = goods[i]
      if (goodsNums[goods_id]) {
        goodsNums[goods_id] += num
      } else {
        goodsNums[goods_id] = num
      }
    }
    return goodsNums
  },

  calcSubNums(goods, goodsId) {
    var subNums = {}
    for (let i = 0, len = goods.length; i < len; i++) {
      let { goods_id, sub_id, num } = goods[i]
      if (goods_id == goodsId) {
        subNums[sub_id] = num
      }
    }
    return subNums
  },
  clearCart(e) {
    this.setData({
      order: initOrder,
      showCart: false
    })
  },
  hideCart(e) {
    this.setData({
      showCart: false
    })
  },
  toggleCart(e) {
    var {
      showCart,
      order: { totalNum }
    } = this.data

    if (totalNum <= 0) {
      return
    }
    this.setData({
      showCart: !showCart
    })
  },
  // 选规格
  showSubGoods(e) {
    var {
      info: { goods_map },
      order
    } = this.data
    var { goodsId } = e.currentTarget.dataset
    var { goods_id, goods_name, sub_goods } = goods_map[goodsId]
    this.setData({
      showSubGoods: true,
      activeSubGoods: {
        goods_name,
        goods_id,
        sub_goods,
        activeIndex: 0,
        subNums: this.calcSubNums(order.goods, goodsId)
      }
    })
  },
  hideSubGoods(e) {
    this.setData({
      showSubGoods: false
    })
  },
  changeSubGoods(e) {
    var { subIndex } = e.currentTarget.dataset
    var { activeSubGoods } = this.data
    activeSubGoods['activeIndex'] = subIndex
    this.setData({
      activeSubGoods
    })
  },
  onPhoneTap(e) {
    var { phone } = e.currentTarget.dataset
    makePhoneCall(phone)
  },

  onScrolltolower(e) {
    var { hasMore, loading } = this.data.review
    if (hasMore && !loading) {
      this.loadReview()
    }
  },
  onAddQuasiOrder(e) {
    var that = this
    var id = this.id
    var { order, loading } = this.data

    app.getLoginInfo(loginInfo => {
      console.log('loginInfo:', loginInfo)
      let order_info = JSON.parse(JSON.stringify(order))
      if (!loginInfo.token) {
        wx.navigateTo({
          url: '/pages/login/login'
        })
        return
      }

      // 同步订单数据
      app.setQuasiOrder(
        Object.assign(order_info, {
          price:
            order_info.price +
            order_info.packagePrice +
            order_info.expressPrice,
          payPrice:
            order_info.payPrice +
            order_info.packagePrice +
            order_info.expressPrice,
          productList: Object.values(order_info.productList)
        })
      )

      console.log('globalData_order:', app.globalData.order)
      wx.navigateTo({
        url: `/pages/order/quasi?id=${id}`
      })
    })
  },
  onShareAppMessage() {
    var {
      info: { id, name }
    } = this.data
    return {
      title: name,
      path: `/pages/shop/show?id=${id}`
    }
  }
})
